import { BaseRoute } from './BaseRoute.js';
import { UserService } from '../service/UserService.js';

export class UserRoutes extends BaseRoute {
    constructor() {
        const userService = new UserService();
        super(userService);
        this.userService = userService;
        this._setupRoutes();
    }

    _setupRoutes() {
        // 获取所有用户
        this.router.get('/', this.asyncHandler(async (req, res) => {
            const { page = 1, limit = 10, search, status, role } = req.query;
            const result = await this.userService.getAllUsers({ page, limit, search, status, role });
            this.success(res, result);
        }));

        // 根据ID获取用户
        this.router.get('/:id', this.validateParams({id: {required: true, type: 'number'}}), this.asyncHandler(async (req, res) => {
            const { id } = req.params;
            const user = await this.userService.getUserById(id);
            this.success(res, user);
        }));

        // 创建新用户
        this.router.post('/', this.asyncHandler(async (req, res) => {
            const userData = req.body;
            const newUser = await this.userService.createUser(userData);
            this.success(res, newUser, 'User created successfully', 201);
        }));

        // 更新用户
        this.router.put('/:id', this.validateParams({id: {required: true, type: 'number'}}), this.asyncHandler(async (req, res) => {
            const { id } = req.params;
            const updateData = req.body;
            const updatedUser = await this.userService.updateUser(id, updateData);
            this.success(res, updatedUser, 'User updated successfully');
        }));

        // 删除用户
        this.router.delete('/:id', this.validateParams({id: {required: true, type: 'number'}}), this.asyncHandler(async (req, res) => {
            const { id } = req.params;
            const deleted = await this.userService.deleteUser(id);
            this.success(res, null, 'User deleted successfully');
        }));

        // 用户登录
        this.router.post('/login', this.asyncHandler(async (req, res) => {
            const loginData = req.body;
            const result = await this.userService.loginUser(loginData);
            this.success(res, result, 'Login successful');
        }));

        // 请求密码重置
        this.router.post('/password-reset', this.asyncHandler(async (req, res) => {
            const resetData = req.body;
            const result = await this.userService.requestPasswordReset(resetData);
            this.success(res, result, 'Password reset email sent');
        }));

        // 更新密码
        this.router.post('/password-update', this.asyncHandler(async (req, res) => {
            const passwordData = req.body;
            const result = await this.userService.updatePassword(passwordData);
            this.success(res, result, 'Password updated successfully');
        }));
     }
 }

// 创建实例并导出路由
const userRoutes = new UserRoutes();
export default userRoutes.getRouter();